package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.Pay;
import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.sql.ResultSetMetaData;
import java.util.List;

/**
 *
 **/

@RestController
public class OrderController {


    //设定一个Url访问订单服务
    //public static final String PaymentSrv_URL = "http://localhost:8001";
    public static final String PaymentSrv_URL = "http://cloud-payment-service";  //起到域名作用   @LoadBalanced 启用客户端负载均衡功能

    @Resource
    private RestTemplate restTemplate;
    //增加
    @PostMapping(value = "/consumer/pay/add")
    public ResultData addOrder(@RequestBody PayDTO payDTO){
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
    }

    //查询
    @GetMapping(value = "/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id){
        return restTemplate.getForObject(PaymentSrv_URL+"/pay/get/"+id,ResultData.class,id);
    }

    //删除
    @DeleteMapping(value = "/consumer/pay/del/{id}")
    public ResultData deleteById(@PathVariable("id") Integer id){
        return restTemplate.exchange(PaymentSrv_URL+"/pay/del/"+id,HttpMethod.DELETE,null,ResultData.class).getBody();
    }

    //修改
    //查询
    @PutMapping(value = "/consumer/pay/update")
    public ResultData updatePay(@RequestBody PayDTO payDTO){
        return restTemplate.exchange(PaymentSrv_URL+"/pay/update", HttpMethod.PUT,  new HttpEntity<>(payDTO),ResultData.class).getBody();
    }

    @GetMapping(value = "/consumer/pay/get/info")
    private String getInfoByConsul(){
        return restTemplate.getForObject(PaymentSrv_URL+"/pay/get/info", String.class);
    }


    /**
     * 修改80微服务的Controller、使用DiscoverClient动态获取线上所有的服务列表
     * 负载均衡原理：默认为轮询Round和随机Random
     */
    @Resource
    private DiscoveryClient discoveryClient;
    @GetMapping("/consumer/discovery")
    public String discovery()
    {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
        }

        return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
    }

}
